package com.myapp.mobilesafe.activity;

import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.myapp.mobilesafe.db.dao.BlackListDao;
import com.myapp.mobilesafe.entity.BlackListInfo;

import java.util.ArrayList;

public class BlackListActivity extends AppCompatActivity {
    private ListView blackList;
    private BlackListDao mDao;
    private ArrayList<BlackListInfo> mList;
    private BlackNumberAdapter mAdapter;
    private ProgressBar pbLoading;
    private int mIndex;// 记录分页查询的位置

    private boolean isLoading;// 标记当前是否正在加载
    private int mTotalCount;// 黑名单总个数
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_black_list);
        blackList = (ListView) findViewById(R.id.lv_black_number);
        mDao = BlackListDao.getInstance(this);
        //有bug记得调试
        mTotalCount = mDao.getTotalCount();
        blackList = (ListView) findViewById(R.id.lv_black_number);
        pbLoading = (ProgressBar) findViewById(R.id.pb_loading);
        initData();
        blackList.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE) {
                    int endPosition = blackList.getLastVisiblePosition();
                    if (endPosition >= mList.size()-1 && !isLoading) {
                        Log.i("hahah", "到底#@#@#@#");
                        if(mList.size()<mTotalCount){
                            initData();
                        }else {
                            Toast.makeText(getApplicationContext(),"没有数据啦！！",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }
    private void initData(){
        isLoading = true;// 表示正在加载
        // 显示进度条
        pbLoading.setVisibility(View.VISIBLE);
        new Thread(){
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
               // mList = mDao.findAll();
                if(mList == null){
                    mList = mDao.findPart(mIndex);
                }else {
                    mList.addAll(mDao.findPart(mIndex));
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(mAdapter==null){
                            mAdapter = new BlackNumberAdapter();
                            blackList.setAdapter(mAdapter);
                        }else {
                            mAdapter.notifyDataSetChanged();
                        }
                        mIndex = mList.size();
                        pbLoading.setVisibility(View.GONE);
                        isLoading=false;
                    }
                });
            }
        }.start();
    }
    static class ViewHolder {
        public TextView tvNumber;
        public TextView tvMode;
        public ImageView ivDelete;
    }
    class BlackNumberAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public BlackListInfo getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        // listview重用
        // 1. 重用convertView, 保证view不会创建多次,造成内存溢出
        // 2. 使用ViewHolder, 减少findviewbyid的次数
        // 3. 将ViewHolder写成static, 保证只在内存中加载一次
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = null;
            ViewHolder holder = null;
            if (convertView == null) {
                view = View.inflate(getApplicationContext(),
                        R.layout.list_item_blacklist, null);

                holder = new ViewHolder();

                TextView tvNumber = (TextView) view
                        .findViewById(R.id.tv_number);
                TextView tvMode = (TextView) view.findViewById(R.id.tv_mode);
                ImageView ivDelete = (ImageView) view
                        .findViewById(R.id.iv_delete);

                holder.tvNumber = tvNumber;
                holder.tvMode = tvMode;
                holder.ivDelete = ivDelete;

                view.setTag(holder);// 将holder对象,通过打标记的方式保存在view中, 和view绑定在一起了
                System.out.println("初始化view");
            } else {
                view = convertView;
                holder = (ViewHolder) view.getTag();// 从view中取出holder对象
                System.out.println("重用view");
            }

            final BlackListInfo info = getItem(position);
            holder.tvNumber.setText(info.number);

            switch (info.mode) {
                case 1:
                    holder.tvMode.setText("拦截电话");
                    break;
                case 2:
                    holder.tvMode.setText("拦截短信");
                    break;
                case 3:
                    holder.tvMode.setText("拦截全部");
                    break;
            }

            // 给删除按钮添加点击事件
            holder.ivDelete.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // 1.从数据库删除
                    // 2.从集合删除
                    // 3.刷机listview
                    mDao.delete(info.number);
                    mList.remove(info);
                    mAdapter.notifyDataSetChanged();
                }
            });

            return view;
        }
    }

    public void addBlackNumber(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final AlertDialog dialog = builder.create();
        View view = View.inflate(this, R.layout.dialog_add_black_number, null);// 给dialog设定特定布局
        // dialog.setView(view);
        dialog.setView(view, 0, 0, 0, 0);// 去掉上下左右边距, 兼容2.x版本

        Button btnOK = (Button) view.findViewById(R.id.btn_ok);
        Button btnCancel = (Button) view.findViewById(R.id.btn_cancel);

        final EditText etBlackNumber = (EditText) view
                .findViewById(R.id.et_black_number);

        final RadioGroup rgGroup = (RadioGroup) view
                .findViewById(R.id.rg_group);

        btnOK.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String phone = etBlackNumber.getText().toString().trim();
                if (!TextUtils.isEmpty(phone)) {
                    int id = rgGroup.getCheckedRadioButtonId();// 获取当前被勾选的radiobutton的id
                    int mode = 1;
                    switch (id) {
                        case R.id.rb_phone:
                            mode = 1;
                            break;
                        case R.id.rb_sms:
                            mode = 2;
                            break;
                        case R.id.rb_all:
                            mode = 3;
                            break;
                    }

                    mDao.add(phone, mode);// 保存到黑名单数据库中

                    // 给集合添加元素
                    BlackListInfo addInfo = new BlackListInfo();
                    addInfo.number = phone;
                    addInfo.mode = mode;

                    // mList.add(addInfo);
                    mList.add(0, addInfo);// 添加到集合的第一个位置

                    // 刷新界面
                    mAdapter.notifyDataSetChanged();

                    dialog.dismiss();
                } else {
                    Toast.makeText(getApplication(),"内容不能为空！！",Toast.LENGTH_SHORT).show();
                }
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();

    }
}
